package sv.com.renacempleo.web.controller.sgd;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import sv.com.renacempleo.dto.ctg.CtgCatalogo;
import sv.com.renacempleo.dto.ctg.CtgOficinas;
import sv.com.renacempleo.dto.sgd.SgdAcceso;
import sv.com.renacempleo.dto.sgd.SgdUsuario;
import sv.com.renacempleo.exception.WebException;
import sv.com.renacempleo.web.controller.BaseController;
import sv.com.renacempleo.web.util.DBContext;
import sv.com.renacempleo.web.util.WebUtilidades;

@Controller
@RequestMapping("/admin/usuarios")
public class SgdUsuarioController extends BaseController implements Serializable{

	private static final long serialVersionUID = 5875106898010264338L;
	
	@RequestMapping(value = "view", method = {RequestMethod.POST})
	public String view(Model model, @RequestParam (required = false) String header) {
		model.addAttribute(WebUtilidades.HEADER_TITLE, StringUtils.isBlank(header) ? "USUARIOS Y ACCESOS" : header);
		try {
			model.addAttribute("data", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllAsArray()));
			model.addAttribute("sgdRoles", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findSgdRolesAsArray()));
		} catch (Exception e) {
			logger.error("model", e);
		}
		return "admin/seguridad/sgdUsuario";
	}
	
	@RequestMapping(value = "save", method = {RequestMethod.POST})
	public void save(
			@ModelAttribute SgdUsuario sgdUsuario,
			HttpServletRequest request,
			HttpServletResponse response)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String jsonString = StringUtils.trimToEmpty(request.getParameter("sgdRoles"));
			List<SgdAcceso> sgdAccesos = new ArrayList<SgdAcceso>();
			if(StringUtils.isNotBlank(jsonString) && !"[]".equals(jsonString)){
				JSONArray jsonArray = JSONArray.fromObject(jsonString);
				JSONObject jsonObject;
				SgdAcceso sgdAcceso = null;
				for (Object object : jsonArray) {
					jsonObject = (JSONObject) object;
					sgdAcceso = new SgdAcceso();
					sgdAcceso.setSgdUsuario(sgdUsuario);
					sgdAcceso.setSgdRol(new CtgCatalogo(new Long(jsonObject.getString("sgdRolId"))));
					if(new Long(jsonObject.getString("sgdAccesoId")) > 0){
						sgdAcceso.setSgdAccesoId(new Long(jsonObject.getString("sgdAccesoId")));
					}
					sgdAcceso.setSgdAccesoAsignado(jsonObject.getString("sgdAccesoAsignado"));
					sgdAccesos.add(sgdAcceso);
				}
			}
			
			// 26-09-2012, agregado por Ricardo Ardon,  para recuperar oficina activa
			CtgOficinas office = new CtgOficinas();
			office.setCtgOficinaId("1");
			sgdUsuario.setCtgOficina(office);
			// EDC - Ricardo Ardon - retomar mas adelante
			
			DBContext.getSgdUsuarioService().saveOrUpdateSgdUsuario(sgdUsuario, sgdAccesos);
			result.put("data", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllAsArray()));
			result.put("dataIndex", sgdUsuario.getSgdUsuarioId());
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("save", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("save", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		result.put("sgdUsuarioId", sgdUsuario.getSgdUsuarioId());
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "findAllSgdRolBySgdUsuarioId", method = {RequestMethod.POST})
	public void findAllSgdRolBySgdUsuarioId(@RequestParam Long sgdUsuarioId,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result.put("sgdRoles", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllSgdRolBySgdUsuarioId(sgdUsuarioId)));
			result.put(SUCCESS, true);
		} catch (WebException e) {
			logger.error("findAllSgdRolBySgdUsuarioId", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("findAllSgdRolBySgdUsuarioId", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "delete", method = {RequestMethod.POST})
	public void delete(@RequestParam Long sgdUsuarioId,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DBContext.getSgdUsuarioService().deleteSgdUsuario(sgdUsuarioId);
			result.put("data", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllAsArray()));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("delete", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("delete", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "toggle", method = {RequestMethod.POST})
	public void toggle(@RequestParam Long sgdUsuarioId,
			@RequestParam String sgdUsuarioActivo,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DBContext.getSgdUsuarioDao().toggleActiveUser(sgdUsuarioId, sgdUsuarioActivo);
			result.put("data", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllAsArray()));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		} catch (WebException e) {
			logger.error("delete", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("delete", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}

}
